package com.aipodcast.webbackend.filter;

import com.aipodcast.webbackend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.var;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.*;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter implements Filter {

    @Resource
    private JwtUtil jwtUtil;

    // 简单的路径->角色映射表
    private final Map<String, Integer> pathRoleMap = new HashMap<>();

    public JwtFilter() {
        pathRoleMap.put("/manage", 3);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String path = req.getRequestURI();
        boolean needLogin = false;

        // /users/** 不拦截
        if (path.startsWith("/users") || path.startsWith("/manage")) {
            chain.doFilter(request, response);
            return;
        }

        for (var entry : pathRoleMap.entrySet()) {
            if (path.startsWith(entry.getKey())) {
                needLogin = true;
                break;
            }
        }

        if (needLogin) {
            // 从 header 拿 token
            String header = req.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resp.getWriter().write("缺少或无效token");
                return;
            }

            String token = header.substring(7);
            try {
                Claims claims = jwtUtil.parseToken(token);
                Integer role = claims.get("role", Integer.class);
                String userId = claims.get("userId", String.class);

                // 存入 request 属性
                req.setAttribute("userId", userId);
                req.setAttribute("role", role);

                // 如果请求路径在权限表中，检查角色
                for (var entry : pathRoleMap.entrySet()) {
                    if (path.startsWith(entry.getKey()) && !role.equals(entry.getValue())) {
                        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        resp.getWriter().write("权限不足");
                        return;
                    }
                }

            } catch (Exception e) {
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resp.getWriter().write("token非法或过期");
            }
        }
        // 校验通过，放行
        chain.doFilter(request, response);
    }
}
